﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.ComponentModel;

namespace ControlExplorer
{
    public class SearchViewModel : INotifyPropertyChanged
    {
        #region ** fields

        private static SearchViewModel _instance = null;
        private bool _showSearchList = false;
        private string _searchCriteria = "";

        #endregion

        #region ** object model

        public static SearchViewModel Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new SearchViewModel();
                return _instance;
            }
        }

        public string SearchCriteria
        {
            get
            {
                return _searchCriteria;
            }
            set
            {
                _searchCriteria = value;
                _showSearchList = SearchList.Count > 0;
                RaisePropertyChanged("SearchCriteria");
                RaisePropertyChanged("SearchList");
                RaisePropertyChanged("ShowSearchList");
            }
        }

        public bool ShowSearchList
        {
            get
            {
                return _showSearchList;
            }
            set
            {
                _showSearchList = value;
                RaisePropertyChanged("ShowSearchList");
            }
        }

        public IList<SearchResult> SearchList
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_searchCriteria))
                    return new List<SearchResult>();

                var searchKeys = _searchCriteria.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                return (from c in MainViewModel.Instance.Controls
                        where searchKeys.Any(key => c.Contains(key))
                        select new SearchResult
                         {
                             Control = c,
                             Features = c.GetAllFeatures().Where(f => f.ContainsAny(searchKeys))
                         }).ToList();
            }
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class SearchResult
    {
        public ControlDescription Control { get; set; }
        public IEnumerable<FeatureDescription> Features { get; set; }
    }
}
